# -*- encoding: utf-8 -*-
'''
Created on 02.08.2009

@author: André Stannek
'''
from os.path import exists

from sqlalchemy import Column, Integer, Text, Table
import mutagen

import settings
from database import Database
import mad

db = Database()

class Audiofile(db.Base):
    __tablename__ = 'audiofiles'
    id = Column(Text, primary_key=True)
    tpe1 = Column(Text)
    tit2 = Column(Text)
    talb = Column(Text)
    trck = Column(Integer)
    popm = Column(Integer)
    apic = Column(Text)
    tlen = Column(Text)
    
    def __init__(self, id, artist, title, album, track, rating, length, cover=None):
        self.id = id
        self.tpe1 = artist
        self.tit2 = title
        self.talb = album
        self.trck = track
        #self.popm = rating
        #self.apic = cover
        self.tlen = length
        
    def get_properties_as_dict(self):
        '''Return properties as dict to make it json compatible.'''
        return {
            'id': self.id,
            'artist' : self.tpe1,
            'title' : self.tit2,
            'album' : self.talb,
            'track' : self.trck,
            'rating' : self.popm,
            'length' : self.tlen,
            'link' : '%s%s' % (settings.BASE_URL, self.id[len(settings.BASE_PUBLIC_DATA_DIR):])
            #'cover' : self.apic
            }


def create_audiofile(path):
	tag = mutagen.id3.ID3(path)
	tag.load(path, translate=True)
	id = path
	try:
		artist = tag.getall('TPE1')[0][0]
	except IndexError:
		artist = 'unknown'
	try:
		title = tag.getall('TIT2')[0][0]
	except IndexError:
		title = ''
	try:
		album = tag.getall('TALB')[0][0]
	except IndexError:
		album = 'unknown'
	try:
		track = int(tag.getall('TRCK')[0][0])
	except (IndexError, ValueError):
		track = 0
	rating = tag.getall('PPOM')
	try:
		length = tag.getall('TLEN')[0][0]
	except IndexError:
		length = -1
	if length <= 0:
		mf = mad.MadFile(path)
		length = mf.total_time()
	cover = tag.getall('APIC')
	return Audiofile(path, artist, title, album, track, rating, length, cover)

def write_rating(path, rating, playcount=0):
	audio = mutagen.id3.ID3(path)
	#audio.setall('POPM', POPM(text=u"default", rating, playcount))
	audio.save()
